//
//  AboutusController.m
//  Contacts
//
//  Created by beisheng03 on 2017/10/25.
//  Copyright © 2017年 beisheng. All rights reserved.
//

#import "AboutusController.h"
#import <WebKit/WebKit.h>
#import "WKDelegateController.h"

@interface AboutusController ()<WKNavigationDelegate,WKScriptMessageHandler,
WKDelegateControllerDelegate>

@property (nonatomic, weak) WKWebView *webView;

@property (nonatomic, strong) WKUserContentController  *userContentController;

@property (nonatomic, weak) UIProgressView *prosess;

@end

@implementation AboutusController


- (UIProgressView *)prosess{
    if (!_prosess) {
        UIProgressView *pro = [[UIProgressView alloc]init];
        _prosess = pro;
        _prosess.progressTintColor = [UIColor redColor];
//        [self.view addSubview:pro];
        
    }
    
    return _prosess;
}


- (WKWebView *)webView{
    
    if (!_webView) {
        //配置环境
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc]init];
        _userContentController = [[WKUserContentController alloc]init];
        //允许视频播放
        config.allowsAirPlayForMediaPlayback = YES;
        // 允许在线播放
        config.allowsInlineMediaPlayback = YES;
        // 允许可以与网页交互，选择视图
        config.selectionGranularity = YES;
        // web内容处理池
        config.processPool = [[WKProcessPool alloc] init];
        // 是否支持记忆读取
        config.suppressesIncrementalRendering = YES;
        
        config.userContentController = _userContentController;
        
        WKWebView *webView = [[WKWebView alloc]initWithFrame:self.view.bounds configuration:config];
        //注册方法
        WKDelegateController *delegateController = [[WKDelegateController alloc]init];
        delegateController.delegate = self;
        [_userContentController addScriptMessageHandler:delegateController name:@"sendMessage"];//注册一个name为sendMessage的js方法
        
        _webView = webView;
        [self.view addSubview:webView];
        
    }
    
    return _webView;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.webView.navigationDelegate = self;
    self.webView.scrollView.showsVerticalScrollIndicator = NO;
    
//    self.automaticallyAdjustsScrollViewInsets = NO;
    if ([self.type isEqualToString:@"dian"]) {
//        self.navigationItem.title = @"帮助";
    } else if ([self.type isEqualToString:@"kefu"]) {
        self.navigationItem.title = @"客服";

    }else{
        
        self.navigationItem.title = @"文章详情";
        
        [self setNav];
        
    }
    
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
//    self.urlString = @"https://www.baidu.com";
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlString]]];
    
    
//    self.prosess.frame = CGRectMake(0, 64, KScreenW, 5);
//    
//    if (IPhoneX) {
//        
//        self.prosess.frame = CGRectMake(0, 88, KScreenW, 5);
//
//    }
    
    
}


- (void)viewWillAppear:(BOOL)animated
{
    
    [super viewWillAppear:animated];

    if ([self.type isEqualToString:@"dian"]) {
        
        [self.navigationController setNavigationBarHidden:NO animated:YES];

    } else if ([self.type isEqualToString:@"kefu"]) {
        
        [self.navigationController setNavigationBarHidden:NO animated:YES];

    }else{
        
        [self.navigationController setNavigationBarHidden:YES animated:YES];

    }
    
    
}


- (void)setNav{
    
    CGFloat navH = IPhoneX ? 88 : 64;
    UIView *navView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenW, navH)];
    navView.backgroundColor = [UIColor whiteColor];
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, navView.height - 0.6, KScreenW, 0.6)];
    lineView.backgroundColor = lineGray;
    [navView addSubview:lineView];
    CGFloat titleY = IPhoneX ? 44 : 20;
    UILabel *tileLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, titleY, 20, 44)];
    
    tileLabel.text = @"文章详情";
    tileLabel.font = MYFONT(17);
    [tileLabel sizeToFit];
    tileLabel.centerX = KScreenW * 0.5;
    tileLabel.top = tileLabel.top + ( (44 - tileLabel.height) * 0.5);
    [navView addSubview:tileLabel];
    
    UIButton *but = [UIButton buttonWithType:UIButtonTypeCustom];
    [but setImage:[UIImage imageNamed:@"nav_backHei"] forState:UIControlStateNormal];
    [but setImage:[UIImage imageNamed:@"nav_backHei"] forState:UIControlStateHighlighted];
    [but addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    but.imageView.contentMode = UIViewContentModeScaleAspectFit;
    
//  but.backgroundColor = [UIColor redColor];
    
    but.frame = CGRectMake(0, titleY, 44, 44);
    but.contentEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
    
    [navView addSubview:but];
    
    [self.view addSubview:navView];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    //    CGFloat navH = IPhoneX ? 44 : 20;
    CGFloat tabbarH = IPhoneX ? 83 : 49;
    if (@available(iOS 11.0, *)) {
        
        //        contentInsetAdjustmentBehavior属性也是用来取代automaticallyAdjustsScrollViewInsets属性的，推荐使用这种方式。
        self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        self.webView.scrollView.contentInset = UIEdgeInsetsMake(navH, 0, tabbarH, 0);
        
        
    }else{
        
        self.webView.scrollView.contentInset = UIEdgeInsetsMake(navH, 0, tabbarH, 0);
    }
}


- (void)back{
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - WKScriptMessageHandler  JS调用OC

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    
    if ([self.type isEqualToString:@"dian"]) {
        
        self.navigationItem.title = self.webView.title;
        
    }
    
    
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    
//    NSInteger type = [message.body integerValue];
//
//    if (type == 2) {
//        [self.navigationController popViewControllerAnimated:YES];
//    }
//
//
//    if (type == 3) {
//        [self.navigationController popViewControllerAnimated:YES];
//    }
    
}


#pragma mark - WKNavigationDelegate
//页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    
    [SVProgressHUD showWithStatus:@"正在加载数据..."];
    
}

//内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
   
    
    
}

//OC调JS方法
//页面加载完成后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    
    [SVProgressHUD dismiss];
    
    //    NSLog(@"%@",[NSString stringWithFormat:@"get_ios_key('%@')",[UserViewModel shareUserViewModel].access_token]);@"get_ios_key('8888888888')"
    //say()是JS方法名，completionHandler是异步回调block
    
    [webView evaluateJavaScript:@"DFSFSD" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        
//        NSLog(@"%@",result);
//        庄配  420621198702231225
//        何剑剑 450803198901126632
//        NSLog(@"%@",[NSThread currentThread]);
        
    }];
    
}

//页面加载失败后调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error{

}


//收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    
    NSLog(@"%@",navigationResponse.response.URL.absoluteString);
    
    if ([navigationResponse.response.URL.absoluteString isEqualToString:@"http://xiaojingsc.test.beisheng.wang/wap/tmpl/cart_list.html"]) {
        decisionHandler(WKNavigationResponsePolicyCancel);
        
    } else {
        
        decisionHandler(WKNavigationResponsePolicyAllow);
        
    }
    
    //允许跳转

}



//发送请求前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    
    //    NSLog(@"%@",navigationAction.request.URL.absoluteString);
    //允许跳转
    decisionHandler(WKNavigationActionPolicyAllow);
    
    //还允许跳转
    //    decisionHandler(WKNavigationActionPolicyCancel);
    
}

- (void)dealloc{
    
    //前面加过的方法一定要remove掉
    [_userContentController removeScriptMessageHandlerForName:@"sendMessage"];
    
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    
    [self.webView removeObserver:self forKeyPath:@"title"];
    
}


- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleDefault;
    
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    
}


@end
